package com.helloworld.demo.jmm;

import sun.misc.Unsafe;

import java.util.concurrent.locks.LockSupport;

public class Test {
    //private volatile boolean flag = true; //volatile 使用了lock指令，该指令的作用是立即将修改的值写回主内存并让所有的工作内存失效，而产生重新加载
    private boolean flag = true;
    private int count = 0;
    //private volatile int count = 0;
    //private Integer count = 0; //Integer 使用了final保证可见性

    public void load() {
        String threadInfo = Thread.currentThread().getName() + " + " + Thread.currentThread().getId();
        System.out.println(threadInfo + "开始执行...");

        while (flag){
            count++;
            //Unsafe.getUnsafe().storeFence();
            //Thread.yield();       //礼让CPU 线程上下文切换
            //System.out.println(count); //synchnized  内存屏障

            //LockSupport.unpark(Thread.currentThread()); //内存屏障
            //shortWait(1000000);
            //shortWait(1000);

           /* try{
                Thread.sleep(1); //内存屏障
            }catch (Exception e){
                e.printStackTrace();
            }*/

            /*long start = System.nanoTime();
            long end;
            do{
                end = System.nanoTime();
            }while(start + 1000000 >= end);*/

            /*long start = System.nanoTime();
            long end = 0;
            while(start + 1000000 >= end){
                end = System.nanoTime();
            }*/

        }



        System.out.println(threadInfo + "跳出循环..." + "count = " + count);
    }

    public void refresh(){
        String threadInfo = Thread.currentThread().getName() + " + " + Thread.currentThread().getId();
        flag = false;
        System.out.println(threadInfo + "修改flag为" + flag);
    }

    public static void main(String[] args) throws InterruptedException {
        Test test = new Test();

        Thread threadA = new Thread(()->
            test.load(),"ThreadA"
        );

        threadA.start();

        Thread.sleep(1000);

        Thread threadB = new Thread(()->{
            test.refresh();
        },"ThreadB");

        threadB.start();
    }

    public static void shortWait(long interval){
        long start = System.nanoTime();
        long end;
        do{
            end = System.nanoTime();
        }while(start + interval >= end);
    }

}
